#include"thread_pool.h"
ThreadPool* ThreadPool::_instance=nullptr;

ThreadPool::ThreadPool(int n)
{
    if(0<n||n>ThreadPool::MAXCOUNT)
        n=10;
    for(int i=0;i<n;++i)
        this->_works.emplace_back(i);
    this->_workstate.assign(size_t(n),false);
}

ThreadPool::~ThreadPool()
{
    close();
}

ThreadPool* ThreadPool::GetInstance(int n)
{
    if(ThreadPool::_instance==nullptr)
        ThreadPool::_instance=new ThreadPool(n);
    return _instance;
}

int ThreadPool::invoke()
{
    int count=0;
    for(size_t i=0;i<_works.size();++i)
        if(_works[i].invoke(*this)==0)
        {
            _workstate[i]=true;
            count++;
        }
    return count;
}

int ThreadPool::close()
{
    int count=0;
    for(size_t i=0;i<_works.size();++i)
        if(_workstate[i]&&_works[i].close()==0)
        {
            _workstate[i]=false;
            count++;
        }
    return count;
}

